package com.menggudf.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.menggudf.common.utils.DateUtils;
import com.menggudf.convert.Illness2Convert;
import com.menggudf.convert.IllnessConvert;
import com.menggudf.dao.CommonSymptomDao;
import com.menggudf.dao.IllnessDao;
import com.menggudf.dao.MedicalDBDao;
import com.menggudf.dao.NewCreatedMedicineDao;
import com.menggudf.dao.PartsDao;
import com.menggudf.dao.SymptomDao;
import com.menggudf.dao.SystemAdminDao;
import com.menggudf.entity.AgeSelect;
import com.menggudf.entity.CommonSymptom;
import com.menggudf.entity.Duration;
import com.menggudf.entity.Illness;
import com.menggudf.entity.MedicalDB;
import com.menggudf.entity.NewCreatedMedicine;
import com.menggudf.entity.Parts;
import com.menggudf.entity.Symptom;
import com.menggudf.entity.SystemAdmin;
import com.menggudf.model.AgeSelectModel;
import com.menggudf.model.CommonSymptomModel;
import com.menggudf.model.ExportIllnessModel;
import com.menggudf.model.Illness2Model;
import com.menggudf.model.IllnessModel;
import com.menggudf.model.ResultModel;
import com.menggudf.model.SymptomDetailModel;
import com.menggudf.model.SymptomModel;
import com.menggudf.service.IllnessService;

@Service
public class IllnessServiceImpl implements IllnessService{
    
    private static final Logger LOGGER = LoggerFactory
            .getLogger(IllnessServiceImpl.class);
    
    private final String[] importArr={
            "疾病名称","一级科目","二级科目","性别","发病时间","发病年龄段","辅助检查","疾病概述","诊疗方案","详细用药",
            "病情分级","限制性症状个数","病症名称","部位","性别","既往病史","诱因","药物服用史","是否重要","限制性症状",
            "分类","病症程度","病症性质","影响因素","病症次数","病症用药","数值下限","数值上限","描述","病情分级"};

    @Autowired
    private IllnessDao illnessDao;
    
    @Autowired
    private SymptomDao symptomDao;
    
    @Autowired
    private PartsDao partsDao;
    
    @Autowired
    IllnessConvert illnessConvert;
    
    @Autowired
    Illness2Convert illness2Convert;
    
    @Autowired
    CommonSymptomDao commonSymptomDao;
    
    @Autowired
    SystemAdminDao systemAdminDao;
    
    @Autowired
    NewCreatedMedicineDao newCreatedMedicineDao;
    
    @Autowired
    MedicalDBDao medicalDBDao;

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel createIllnessRecort(
            String illness,
            String symptoms,
            String parts,
            String specialCrowd,
            String levelOneSubject,
            String levelTwoSubject,
            String diseaseAge,
            String author,
            String examNames,
            Boolean isInjured,
            String duration,
            String pathogen, String scheme, String medicine) {
        return ResultModel.fail();
    }
    
    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllnessList(
            String illName,
            String symptomName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            Date startTime,
            Date endTime,
            String diseaseAge,
            int pageSize,
            int offset) {
        List<Illness> ills = illnessDao.getIllnessList(
                illName, symptomName, parts, levelOneSubject, levelTwoSubject, DateUtils.dateFormat(startTime), DateUtils.dateFormat(endTime), diseaseAge, pageSize, offset);
        long count = illnessDao.getIllnessListCount(
                illName, symptomName, parts, levelOneSubject, levelTwoSubject,DateUtils.dateFormat(startTime), DateUtils.dateFormat(endTime), diseaseAge);
        List<IllnessModel> iModels = new ArrayList<IllnessModel>();
        for(Illness il : ills){
            IllnessModel iModel = illnessConvert.entity2IllnessModelConvert(il);
            iModels.add(iModel);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", count);
        map.put("rows", iModels);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public IllnessModel getIllnessDetail(String illness) {
        Illness ill = illnessDao.getIllnessRecortByIllness(illness);
        IllnessModel illModel = new IllnessModel();
        if(ill!=null){
            illModel = illnessConvert.entity2IllnessModelConvert(ill);
        }
        return illModel;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllByparts(String parts) {
        List<Illness> ills = illnessDao.getIllByparts(parts);
        List<String> illList = new ArrayList<String>();
        List<Integer> idList = new ArrayList<Integer>(); 
        for(Illness i : ills){
            illList.add(i.getIllness());
            idList.add(i.getId());
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("ills", illList);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String,Object> getSymptomsByillList(String ids) {
        List<Illness> list = illnessDao.getIllnessRecortByIds(ids);
        Set<String> set = new HashSet<String>();
        for(Illness i : list){
            for(Symptom s : i.getSymptoms()){
                set.add(s.getSymptom());
            }
        }
        List<String> symotoms = new ArrayList<String>();
        symotoms.addAll(set);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("symptoms", symotoms);
        map.put("ids", ids);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllByIdAndsymptoms(
            String symptom, String symptoms, String ids,
            String temperature, String sYS,String dIA, String pulse, 
            String degree, String nature, String times) {
        List<Illness> ills = new ArrayList<Illness>();
        if(StringUtils.hasText(symptom)){
            ills  = illnessDao.getIllByIdAndsymptoms(
                    symptom,ids,temperature,sYS,dIA,pulse,degree,nature,times);
        }
        String[] sym = null ;
        if(symptoms.indexOf("\\s+|[，,]")==-1){
            sym = symptoms.split("\\s+|[，,]");
        }else{
            sym[0] = symptoms;
        }
        
        List<Integer> idList = new ArrayList<Integer>();
        Set<String> set = new HashSet<String>();
        for(Illness il : ills){
            idList.add(il.getId());
            for(Symptom s : il.getSymptoms()){
                if(!Arrays.asList(sym).contains(s.getSymptom())){
                    set.add(s.getSymptom());
                }
            }
        }
        List<String> syms = new ArrayList<String>();
        syms.addAll(set);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("syms", syms);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public IllnessModel getIllnessById(String id) {
        Illness il = illnessDao.getIllnessById(id);
        IllnessModel iModel = illnessConvert.entity2IllnessModelConvert(il);
        return iModel;
    }
   
    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllByIdAndsymptomsNo(String symptom, String symptoms, String ids) {
        List<Illness> ills = new ArrayList<Illness>();
/*        if(!CommonUtils.isEmpty(symptom)){
            ills  = illnessDao.getIllByIdAndsymptoms(symptom,ids);
        }*/
        
        List<String> idss = new ArrayList<String>();
        if(ids.indexOf("\\s+|[，,]")==-1){
            idss = Arrays.asList(ids.split("\\s+|[，,]"));
        }else{
            idss.add(ids);
        }
        List<String> arrayList = new ArrayList(idss);
        List<String> iList = new ArrayList<String>();
        for(Illness il : ills){
            iList.add(il.getId().toString());
        }
        
        arrayList.removeAll(iList);
        List<Illness> reills = new ArrayList<Illness>();
        if(arrayList!=null && arrayList.size()>0){
            String str = arrayList.toString();
            reills  = illnessDao.getIllnessRecortByIds(str.substring(1, str.length()-1));
        }
        
        String[] sym = null ;
        if(symptoms.indexOf("\\s+|[，,]")==-1){
            sym = symptoms.split("\\s+|[，,]");
        }else{
            sym[0] = symptoms;
        }
        
        List<Integer> idList = new ArrayList<Integer>();
        Set<String> set = new HashSet<String>();
        for(Illness illl : reills){
            idList.add(illl.getId());
            for(Symptom s : illl.getSymptoms()){
                if(!Arrays.asList(sym).contains(s.getSymptom())){
                    set.add(s.getSymptom());
                }
            }
        }
        List<String> syms = new ArrayList<String>();
        syms.addAll(set);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("syms", syms);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public List<IllnessModel> getillsByIds(String ids) {
        List<Illness> il = illnessDao.getIllnessRecortByIds(ids);
        List<IllnessModel> iModels = new ArrayList<IllnessModel>();
        for(Illness i : il){
            IllnessModel iModel = new IllnessModel();
            iModel = illnessConvert.entity2IllnessModelConvert(i);
            iModels.add(iModel);
        }
        return iModels;
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel editIllnessRecort(
            String illness,
            String symptoms,
            String parts,
            String specialCrowd,
            String levelOneSubject,
            String levelTwoSubject,
            String diseaseAge,
            String author,
            String examNames,
            Boolean isInjured,
            String duration,String pathogen, String scheme, String medicine) {
        Illness ill = illnessDao.getIllnessRecortByIllness(illness);
        if(ill==null){
            return ResultModel.fail();
        }
        
        /*try {
            if(author.equalsIgnoreCase("superAdmin") || author.equalsIgnoreCase(ill.getAuthor())){
                ill.setIllness(illness);
                ill.setParts(parts);
                ill.setSpecialCrowd(specialCrowd);
                ill.setModifyTime(new Date());
                ill.setAuthor(author);
                ill.setIsInjured(isInjured);
                ill.setDuration(duration);
                ill.setPathogen(pathogen);
                ill.setScheme(scheme);
                ill.setMedicine(medicine);
                if(!CommonUtils.isEmpty(diseaseAge)){
                    String[] ages = diseaseAge.split("\\s+|[，,]");
                    ill.setDiseaseStartTime(Integer.valueOf(ages[0]));
                    ill.setDiseaseEndTime(Integer.valueOf(ages[1]));
                }else{
                    ill.setDiseaseStartTime(Integer.valueOf(0));
                    ill.setDiseaseEndTime(Integer.valueOf(200));
                }
                ill.setLevelOneSubject(levelOneSubject);
                ill.setLevelTwoSubject(levelTwoSubject);
                Set<Symptom> symptomss = new HashSet<Symptom>();
                String[] list = symptoms.split("\\s+|[，,]");
                for(String sym :list){
                    Symptom symptom = new Symptom();
                    symptom.setSymptom(sym);
                    symptom.setIllness(ill);
                    symptomss.add(symptom);
                }
                ill.setSymptoms(symptomss);
                
                Set<Parts> partss = new HashSet<Parts>();
                String[] list1 = parts.split("\\s+|[，,]");
                for(String s :list1){
                    Parts p = new Parts();
                    p.setPart(s);
                    p.setIllness(ill);
                    partss.add(p);
                }
                ill.setPartss(partss);
                
                ill.setAssistantExam(examNames);
                illnessDao.saveOrUpdate(ill);
                return ResultModel.success();
            }else{
                return ResultModel.fail();
            }
        } catch (Exception e) {
            LOGGER.error("editIllnessRecort fail",e);
        }*/
        
        return ResultModel.fail();
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllnessInParts(
            String parts,
            int sex,
            int isInjured,
            int diseaseAge,
            String temperature,
            String sYS,
            String dIA,
            String pulse,
            int type) {
        Map<String, Object> map = new HashMap<String, Object>();
        String[] ages = null;
        List<Illness> ills = illnessDao.getIllnessInParts(parts,sex,isInjured,diseaseAge,temperature,sYS,dIA,pulse,type);
        List<String> illList = new ArrayList<String>();
        List<Integer> idList = new ArrayList<Integer>(); 
        for(Illness i : ills){
            illList.add(i.getIllness());
            idList.add(i.getId());
        }
        
        map.put("ills", illList);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Illness2Model getIllness2ById(String id) {
        Illness il = illnessDao.getIllnessById(id);
        Illness2Model iModel = illness2Convert.entity2IllnessModelConvert(il);
        return iModel;
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel deleteIll(String illness) {
        Illness il = illnessDao.getIllnessRecortByIllness(illness);
        try {
            illnessDao.remove(il);
            return ResultModel.success();
        } catch (Exception e) {
            LOGGER.error("deleteIll fail!",e);
        }
        return ResultModel.fail();
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel deleteSymptom(String illness) {
        Illness il = illnessDao.getIllnessRecortByIllness(illness);
        if(il!=null){
            List<Symptom> list = symptomDao.getByID(il.getId());
            try {
                for(Symptom s : list){
                    symptomDao.remove(s);
                }
                return ResultModel.success();
            } catch (Exception e) {
                LOGGER.error("deleteSymptom fail",e);
            }
        }else{
            return ResultModel.fail();
        }
        return ResultModel.fail();
        
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel deleteParts(String illness) {
        Illness il = illnessDao.getIllnessRecortByIllness(illness);
        if(il!=null){
            List<Parts> list = partsDao.getByID(il.getId());
            try {
                for(Parts p : list){
                    partsDao.remove(p);
                }
                return ResultModel.success();
            } catch (Exception e) {
                LOGGER.error("deleteParts fail",e);
                return ResultModel.fail();
            }
        }else{
            return ResultModel.fail();
        }
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public List<String> getExamByillList(String ids) {
        List<Illness> list = illnessDao.getIllnessRecortByIds(ids);
        List<String> ss = new ArrayList<String>();
        for(Illness i : list){
            String s = i.getAssistantExam();
            if(s.indexOf("\\s+|[，,]")==-1){
                String[] strs = s.split("\\s+|[，,]");
                for(String q : strs){
                    ss.add(q);
                }
            }else{
                ss.add(s);
            }
        }
        return ss;

    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel addIll(IllnessModel illnessModel) {
        Illness ill = new Illness();
        ill.setAssistantExam(illnessModel.getAssistantExam());
        ill.setCreateTime(new Date());
        ill.setDuration(illnessModel.getDuration());
        ill.setIllness(illnessModel.getIllness());
        ill.setLevelOneSubject(illnessModel.getLevelOneSubject());
        ill.setLevelTwoSubject(illnessModel.getLevelTwoSubject());
        ill.setMedicine(illnessModel.getMedicine());
        ill.setPathogen(illnessModel.getPathogen());
        ill.setScheme(illnessModel.getScheme());
        ill.setSex(illnessModel.getSex());
        List<AgeSelectModel> as = illnessModel.getAges();
        for(AgeSelectModel a : as){
            AgeSelect aa = new AgeSelect();
            aa.setIllness(ill);
            aa.setAgeOption(a.getAgeOption());
            ill.getAges().add(aa);
        }
/*        List<PartsModel> ps = illnessModel.getPartss();
        for(PartsModel p : ps){
            Parts pp = new Parts();
            pp.setPart(p.getPart());
            pp.setIllness(ill);
            ill.getPartss().add(pp);
        }*/
        List<SymptomModel> ss = illnessModel.getSymptoms();
        for(SymptomModel s :ss){
            Symptom sym = new Symptom();
            sym.setSymptom(s.getSymptom());
            sym.setDegree(s.getDegree());
            sym.setMedicine(s.getMedicine());
            sym.setNature(s.getNature());
            sym.setTimes(s.getTimes());
            sym.setSdown(s.getSdown());
            sym.setSup(s.getSup());
            sym.setImgurl(s.getImgurl());
            sym.setParts(s.getParts());
            sym.setDescription(s.getDescription());
            sym.setIllness(ill);
            ill.getSymptoms().add(sym);
        }
        try {
            illnessDao.persist(ill);
            return ResultModel.success();
        } catch (Exception e) {
            LOGGER.error("addIll fail",e);
            return ResultModel.fail("addIll fail", null);
        }
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public List<SymptomModel> getSymptoms(String ids, String symptom) {
        List<Symptom> list = symptomDao.findBySymptom(ids,symptom);
        List<SymptomModel> mlist = new ArrayList<SymptomModel>();
        for(Symptom s : list){
            SymptomModel sym = new SymptomModel();
            sym.setSymptom(s.getSymptom());
            sym.setDegree(s.getDegree());
            sym.setMedicine(s.getMedicine());
            sym.setNature(s.getNature());
            sym.setTimes(s.getTimes());
            sym.setSdown(s.getSdown());
            sym.setSup(s.getSup());
            sym.setImgurl(s.getImgurl());
            sym.setParts(s.getParts());
            sym.setDescription(s.getDescription());
            
            sym.setHistorySort(s.getHistorySort());
            sym.setIncentive(s.getIncentive());
            sym.setIsImportant(s.getIsImportant());
            sym.setMedicineHistory(s.getMedicineHistory());
            sym.setPastHistory(s.getPastHistory());
            mlist.add(sym);
        }
        return mlist;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllnessBySexAndAge(Integer sex, Integer age) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Illness> ills = illnessDao.getIllnessBySexAndAge(sex,age);
        List<String> illList = new ArrayList<String>();
        List<Integer> idList = new ArrayList<Integer>(); 
        for(Illness i : ills){
            illList.add(i.getIllness());
            idList.add(i.getId());
        }
        
        map.put("ills", illList);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllnessByIdsAndSymptom(
            String ids,
            String symptom,
            Integer value) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Illness> ills = illnessDao.getIllnessByIdsAndSymptom(ids,symptom,value);
        List<String> illList = new ArrayList<String>();
        List<Integer> idList = new ArrayList<Integer>(); 
        for(Illness i : ills){
            illList.add(i.getIllness());
            idList.add(i.getId());
        }
        
        map.put("ills", illList);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllnessByPart(String ids, String part) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Illness> ills = illnessDao.getIllnessByPart(ids,part);
        List<String> illList = new ArrayList<String>();
        List<Integer> idList = new ArrayList<Integer>(); 
        for(Illness i : ills){
            illList.add(i.getIllness());
            idList.add(i.getId());
        }
        
        map.put("ills", illList);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllByIdAndsymptomsYes(
            String symptom,
            String symptoms,
            String ids,
            Integer value,
            String degree,
            String nature,
            String times) {
        List<Illness> ills = new ArrayList<Illness>();
        if(StringUtils.hasText(symptom)){
            ills  = illnessDao.getIllByIdAndsymptomsYes(
                    symptom,ids,value,degree,nature,times);
        }
        String[] sym = null ;
        if(symptoms.indexOf("\\s+|[，,]")==-1){
            sym = symptoms.split("\\s+|[，,]");
        }else{
            sym[0] = symptoms;
        }
        
        List<Integer> idList = new ArrayList<Integer>();
        Set<String> set = new HashSet<String>();
        for(Illness il : ills){
            idList.add(il.getId());
            for(Symptom s : il.getSymptoms()){
                if(!Arrays.asList(sym).contains(s.getSymptom())){
                    set.add(s.getSymptom());
                }
            }
        }
        List<String> syms = new ArrayList<String>();
        syms.addAll(set);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("syms", syms);
        map.put("ids", idList);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel editIllness(
            String illness,
            Integer sex,
            String levelOneSubject,
            String levelTwoSubject,
            String assistantExam,
            String duration,
            String pathogen,
            String scheme,
            String medicine) {
        Illness ill = illnessDao.getIllnessRecortByIllness(illness);
        if(!StringUtils.isEmpty(levelOneSubject)){
            ill.setLevelOneSubject(levelOneSubject);
        }
        if(!StringUtils.isEmpty(levelTwoSubject)){
            ill.setLevelTwoSubject(levelTwoSubject);
        }
        if(!StringUtils.isEmpty(assistantExam)){
            ill.setAssistantExam(assistantExam);
        }
        if(!StringUtils.isEmpty(duration)){
            ill.setDuration(duration);
        }
        if(!StringUtils.isEmpty(pathogen)){
            ill.setPathogen(pathogen);
        }
        if(!StringUtils.isEmpty(scheme)){
            ill.setScheme(scheme);
        }
        if(!StringUtils.isEmpty(medicine)){
            ill.setMedicine(medicine);
        }
        if(!StringUtils.isEmpty(sex)){
            ill.setSex(sex);
        }
        ill.setModifyTime(new Date());
        try {
            illnessDao.merge(ill);
            return ResultModel.success();
        } catch (Exception e) {
            LOGGER.error("editIllness fail",e);
        }
        return ResultModel.fail();
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel editSym(
            String illness,
            String symptom,
            String degree,
            String nature,
            String times,
            String medicine,
            Double sdown,
            Double sup,
            String imgurl,
            Integer id,
            String parts,String description) {
        Illness ill = illnessDao.getIllnessRecortByIllness(illness);
        Set<Symptom> ss = ill.getSymptoms();
        for(Symptom s : ss){
            if(s.getId()==id){
                if(!StringUtils.isEmpty(degree)){
                    s.setDegree(degree);
                }
                if(!StringUtils.isEmpty(nature)){
                    s.setNature(nature);
                }
                if(!StringUtils.isEmpty(times)){
                    s.setTimes(times);
                }
                if(!StringUtils.isEmpty(medicine)){
                    s.setMedicine(medicine);
                }
                if(!StringUtils.isEmpty(sdown)){
                    s.setSdown(sdown);
                }
                if(!StringUtils.isEmpty(sup)){
                    s.setSup(sup);
                }
                if(!StringUtils.isEmpty(imgurl)){
                    s.setImgurl(imgurl);
                }
                if(!StringUtils.isEmpty(parts)){
                    s.setParts(parts);
                }
                if(!StringUtils.isEmpty(description)){
                    s.setDescription(description);
                }
                if(!StringUtils.isEmpty(symptom)){
                    s.setSymptom(symptom);
                }
                s.setIllness(ill);
                try {
                    symptomDao.merge(s);
                    return ResultModel.success();
                } catch (Exception e) {
                    LOGGER.error("editSym fail",e);
                }
            }
        }
        return ResultModel.fail();
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel editPart(String illness, String part, Integer id) {
/*        Illness ill = illnessDao.getIllnessRecortByIllness(illness);
        Set<Parts> ps = ill.getPartss();
        for(Parts p : ps){
            if(p.getId()==id){
                if(!StringUtils.isEmpty(part)){
                    p.setPart(part);
                    p.setIllness(ill);
                    try {
                        partsDao.merge(p);
                        return ResultModel.success();
                    } catch (Exception e) {
                        LOGGER.error("editPart fail",e);
                    }
                }
            }
        }*/
        return ResultModel.fail();
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getSymptomsByPart(String ids, String part) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Illness> ills = illnessDao.getSymptomsByPart(ids,part);
        List<String> symptoms = new ArrayList<String>();
        Set<String> set = new HashSet<String>();
        for(Illness i : ills){
            for(Symptom s : i.getSymptoms()){
                if(s.getParts().equalsIgnoreCase(part)){
                    set.add(s.getSymptom());
                }
            }
        }
        symptoms.addAll(set);
        map.put("symptoms", symptoms);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public ResultModel getIllByIdAndsymptomsAndPart(
            String symptom,
            String ids,
            String degree,
            String nature,
            String times,
            String imgurl,
            String part,
            String pastHistory,
            String incentive,
            String medicineHistory,
            Integer isImportant,
            Double tp, String factor) {
        List<Illness> ills = illnessDao.getIllByIdAndsymptomsAndPart(
                symptom,ids,degree,nature,times,imgurl,part,pastHistory,incentive,medicineHistory,isImportant,tp,factor);
        List<Integer> list = new ArrayList<Integer>();
        for(Illness i : ills){
            list.add(i.getId());
        }
        return ResultModel.success("获取成功", list);
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public List<String> getSympByLike(String symp) {
        List<String> list = symptomDao.getSympByLike(symp);
        Set<String> symps = new HashSet<String>();
        for(String s : list){
            symps.add(s);
        }
        List<String> symotoms = new ArrayList<String>();
        symotoms.addAll(symps);
        return symotoms;
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getSymptomList(
            String symptom, int pageSize, int offset) {
        List<String> list = symptomDao.getSymptomList(symptom,pageSize,offset);
        long count = symptomDao.getSymptomListCount(symptom);
        List<CommonSymptomModel> mlist = new ArrayList<CommonSymptomModel>();
        for(String s : list){
            CommonSymptom cs = commonSymptomDao.findBySymptom(s);
            CommonSymptomModel csm = new CommonSymptomModel();
            if(cs!=null){
                csm.setAdminCode(cs.getAdminCode());
                csm.setCreatedTime(cs.getCreatedTime());
                csm.setId(cs.getId());
                csm.setSymptom(s);
            }else{
                csm.setSymptom(s);
            }
            //获取ill
            List<Illness> ills = illnessDao.getillNamesBySymptom(s);
            List<SymptomDetailModel> symptomDetailModelList = new ArrayList<SymptomDetailModel>();
            for(Illness i : ills){
                SymptomDetailModel sdmodel = new SymptomDetailModel();
                Set<Symptom> symps = i.getSymptoms();
                SystemAdmin sys = systemAdminDao.findByAdminCode(i.getAuthor());
                Set<String> torySortSet = new HashSet<String>();
                for(Symptom symp : symps){
                    if(s.equalsIgnoreCase(symp.getSymptom())){
                        if(symp.getHistorySort()==0){
                            
                        }else if(symp.getHistorySort()==1){
                            torySortSet.add("既往史");
                        }else if(symp.getHistorySort()==2){
                            torySortSet.add("诱因");
                        }else if(symp.getHistorySort()==3){
                            torySortSet.add("药物服用史");
                        }else{
                            torySortSet.add("错误");
                        }
                    }
                }
                sdmodel.setAdminName(sys.getAdminName());
                sdmodel.setHistorySorts(torySortSet);
                sdmodel.setIllName(i.getIllness());
                symptomDetailModelList.add(sdmodel);
            }
            csm.setDetails(symptomDetailModelList);
            mlist.add(csm);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", count);
        map.put("rows", mlist);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel setSymptomCommon(String symptom, String adminName) {
        CommonSymptom cs = commonSymptomDao.findBySymptom(symptom);
        if(cs!=null){
            return ResultModel.fail("已是常见", null);
        }
        try {
            CommonSymptom newcs = new CommonSymptom();
            newcs.setAdminCode(adminName);
            newcs.setCreatedTime(new Date());
            newcs.setSymptom(symptom);
            commonSymptomDao.persist(newcs);
            return ResultModel.success("设置成功", null);
        } catch (Exception e) {
            LOGGER.error("setSymptomCommon fail",e);
        }
        return ResultModel.fail("设置失败", null);
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel setSymptomCommonNot(String symptom) {
        CommonSymptom cs = commonSymptomDao.findBySymptom(symptom);
        if(cs==null){
            return ResultModel.fail("已是非常见", null);
        }
        try {
            commonSymptomDao.remove(cs);
            return ResultModel.success("设置成功", null);
        } catch (Exception e) {
            LOGGER.error("setSymptomCommonNot fail",e);
        }
        return ResultModel.fail("设置失败", null);
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public List<CommonSymptom> getAllCommonSymptom() {
        return commonSymptomDao.getAllCommonSymptom();
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public boolean hasSymptom(String symptom) {
        return symptomDao.hasSymptom(symptom);
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public void deleteCommonSymptomByIds(List<Integer> ids) {
        commonSymptomDao.deleteCommonSymptomByIds(ids);
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public List<String> getCommonSymp() {
        return commonSymptomDao.getCommonSymp();
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public Map<String, Object> getIllnessList(
            String illName,
            String symptomName,
            String parts,
            String levelOneSubject,
            String levelTwoSubject,
            Date startTime,
            Date endTime,
            String diseaseAge,
            int pageSize,
            int offset,
            String adminCode) {
        SystemAdmin s = systemAdminDao.findByAdminCode(adminCode);
        List<Illness> ills;
        long count;
        if(s!=null && s.getFlag()==1){
            ills = illnessDao.getIllnessList(
                    illName, symptomName, parts, levelOneSubject, levelTwoSubject, DateUtils.dateFormat(startTime), DateUtils.dateFormat(endTime), diseaseAge, pageSize, offset);
            count = illnessDao.getIllnessListCount(
                    illName, symptomName, parts, levelOneSubject, levelTwoSubject,DateUtils.dateFormat(startTime), DateUtils.dateFormat(endTime), diseaseAge);

        }else{
            ills = illnessDao.getIllnessList(
                    illName, symptomName, parts, levelOneSubject, levelTwoSubject, 
                    DateUtils.dateFormat(startTime), DateUtils.dateFormat(endTime), 
                    diseaseAge, pageSize, offset,adminCode);
            count = illnessDao.getIllnessListCount(
                    illName, symptomName, parts, levelOneSubject, levelTwoSubject,
                    DateUtils.dateFormat(startTime), DateUtils.dateFormat(endTime), diseaseAge,adminCode);
        }

        List<IllnessModel> iModels = new ArrayList<IllnessModel>();
        for(Illness il : ills){
            IllnessModel iModel = illnessConvert.entity2IllnessModelConvert(il);
            if(il.getAuthor()!=null){
                SystemAdmin sa = systemAdminDao.findByAdminCode(il.getAuthor());
                if(sa!=null){
                    iModel.setAuthor(sa.getAdminName());
                }else{
                    iModel.setAuthor("");
                }
            }
            
            iModels.add(iModel);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total", count);
        map.put("rows", iModels);
        return map;
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel importExcel(MultipartFile file,String adminCode) {
        FileInputStream fileIn;
        
        CommonsMultipartFile cf= (CommonsMultipartFile)file; 
        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
        File f = fi.getStoreLocation();
        try {
            fileIn = new FileInputStream(f);
          //根据指定的文件输入流导入Excel从而产生Workbook对象  
            Workbook wb0 = WorkbookFactory.create(fileIn);  
            /*Workbook wb0 = new HSSFWorkbook(fileIn);  */
            //获取Excel文档中的第一个表单  
            Sheet sht0 = wb0.getSheetAt(0); 
            int sum = sht0.getLastRowNum();
            Illness ill = new Illness();
            Set<Parts> parts = new HashSet<Parts>();
            Set<Symptom> syms = new HashSet<Symptom>();
            Set<AgeSelect> ages = new HashSet<AgeSelect>();
            Set<Duration> durations = new HashSet<Duration>();
            Set<String> medicines = new HashSet<String>();
            boolean isAllAges = false;
            //对Sheet中的每一行进行迭代  
            for (Row r : sht0) {
                if(r.getRowNum()==0){
                    for(int i=0;i<importArr.length;i++){
                        if(!r.getCell(i).toString().equalsIgnoreCase(importArr[i])){
                            return ResultModel.fail("importExcel error:["+importArr[i]+"]一栏输入错误", null);
                        }
                    }
                    continue;
                }
                
                //如果当前行的行号（从0开始）未达到2（第三行）则从新循环  
                if(r.getRowNum()<1){  
                    continue;  
                }  
                
                if(r.getRowNum()>sum){
                    break;
                }

                if(r.getCell(0)!=null && ill.getIllness()==null){
                    String i = r.getCell(0).toString();
                    Illness il = illnessDao.getIllnessRecortByIllness(i);
                    if(il==null){
                        ill.setIllness(i);
                    }else{
                        return ResultModel.fail("疾病已存在", null);
                    }
                }
                if(r.getCell(1)!=null && ill.getLevelOneSubject()==null){
                    String l = r.getCell(1).toString();
                    if(!StringUtils.isEmpty(l)){
                        ill.setLevelOneSubject(l);
                    }
                }
                if(r.getCell(2)!=null && ill.getLevelTwoSubject()==null){
                    String s1 = r.getCell(2).toString();
                    if(!StringUtils.isEmpty(s1)){
                        ill.setLevelTwoSubject(s1);
                    }
                }
                
                ill.setSex(2);//设置默认值
                if(r.getCell(3)!=null){
                    String sex = r.getCell(3).toString();
                    if(sex!=null && sex!=""){
                        if(sex.equalsIgnoreCase("男")){
                            ill.setSex(0);
                        }else if(sex.equalsIgnoreCase("女")){
                            ill.setSex(1);
                        }else{
                            ill.setSex(2);
                        }
                    }
                }else{
                    ill.setSex(2);
                }
/*                if(r.getCell(4)!=null && ill.getDuration()==null){
                    ill.setDuration(r.getCell(4).toString());
                }*/
                
                if(r.getCell(4)!=null){
                    String duration = r.getCell(4).toString();
                    if(duration!=null && duration!=""){
                        Duration d = new Duration();
                        d.setDuration(duration);
                        d.setIllness(ill);
                        durations.add(d);
                    }
                }
                
                if(r.getCell(5)!=null){
                    String age = r.getCell(5).toString();
                    if(age!=null && age!=""){
                        AgeSelect a = new AgeSelect();
                        a.setIllness(ill);
                        if(age.equalsIgnoreCase("0-30天")){
                            a.setAgeOption(1);
                        }if(age.equalsIgnoreCase("31天-3岁")){
                            a.setAgeOption(2);
                        }if(age.equalsIgnoreCase("4-8岁")){
                            a.setAgeOption(3);
                        }if(age.equalsIgnoreCase("9-13岁")){
                            a.setAgeOption(4);
                        }if(age.equalsIgnoreCase("14-35岁")){
                            a.setAgeOption(5);
                        }if(age.equalsIgnoreCase("36-65岁")){
                            a.setAgeOption(6);
                        }if(age.equalsIgnoreCase("66岁以上")){
                            a.setAgeOption(7);
                        }if(age.equalsIgnoreCase("全年龄段")){
                            isAllAges = true;
                        }else{
                            isAllAges = true;
                        }
                        if(a.getAgeOption()!=null){
                            ages.add(a);
                        }
                    }
                }
                if(r.getCell(6)!=null && ill.getAssistantExam()==null){
                    String s2 = r.getCell(6).toString();
                    if(!StringUtils.isEmpty(s2)){
                        ill.setAssistantExam(s2);
                    }
                }
                if(r.getCell(7)!=null && ill.getPathogen()==null){
                    String s3 = r.getCell(7).toString();
                    if(!StringUtils.isEmpty(s3)){
                        ill.setPathogen(s3);
                    }
                }
                if(r.getCell(8)!=null && ill.getScheme()==null){
                    String s4 = r.getCell(8).toString();
                    if(!StringUtils.isEmpty(s4)){
                        ill.setScheme(s4);
                    }
                }
                if(r.getCell(9)!=null && ill.getMedicine()==null){
                    String med = r.getCell(9).toString();
                    if(med!="" && med!=null){
                        String me = med.replaceAll("（","\\(").replaceAll("）","\\)").replaceAll("，",",");
                        ill.setMedicine(me);
                        String[] a = me.split("、");
                        if(a.length>0){
                            for(String aa : a){
                                String aaa = aa.replaceAll("\\(|\\)", "");
                                String[] b = aaa.split(",");
                                for(String bb : b){
                                    if(bb!=""){
                                        medicines.add(bb);
                                    }
                                }
                            }
                        }
                    }
                }
                if(r.getCell(10)!=null && ill.getWarning()==null){
                    ill.setWarning((int)r.getCell(10).getNumericCellValue());
                }
                
/*                if(r.getCell(11)!=null && ill.getWarning()==null){
                    ill.setLimitSymptoms(r.getCell(11).toString());
                }*/
                if(r.getCell(11)!=null && ill.getWarning()==null){
                    ill.setLimitNum((int)r.getCell(11).getNumericCellValue());
                }
                
                if(r.getCell(12)!=null){
                    String ss = r.getCell(12).toString();
                    if(ss!=null && ss!=""){
                        Symptom s = new Symptom();
                        s.setSymptom(ss);
                        s.setIllness(ill);
                        
                        s.setParts("其它");//设置默认值
                        if(r.getCell(13)!=null){
                            s.setParts(r.getCell(13).toString());
                        }else{
                            s.setParts("其它");
                        }
                        
                        s.setSex(2);//设置默认值
                        if(r.getCell(14)!=null){
                            String sex1 = r.getCell(14).toString();
                            if(sex1!=null && sex1!=""){
                                if(sex1.equalsIgnoreCase("男")){
                                    s.setSex(0);
                                }else if(sex1.equalsIgnoreCase("女")){
                                    s.setSex(1);
                                }else{
                                    s.setSex(2);
                                }
                            }
                        }else{
                            s.setSex(2);
                        }
                        
                        if(r.getCell(15)!=null){
                            s.setPastHistory(r.getCell(15).toString());
                        }
                        if(r.getCell(16)!=null){
                            s.setIncentive(r.getCell(16).toString());
                        }
                        if(r.getCell(17)!=null){
                            s.setMedicineHistory(r.getCell(17).toString());
                        }
                        
                        s.setIsImportant(1);//设置默认值
                        if(r.getCell(18)!=null){
                            String value = r.getCell(18).toString();
                            if(value.equalsIgnoreCase("是")){
                                s.setIsImportant(0);
                            }else{
                                s.setIsImportant(1);
                            }
                        }else{
                            s.setIsImportant(1);
                        }
                        
                        s.setLimitSymptoms(1);//设置默认值
                        if(r.getCell(19)!=null){
                            String value = r.getCell(19).toString();
                            if(value.equalsIgnoreCase("是")){
                                s.setLimitSymptoms(0);
                            }else{
                                s.setLimitSymptoms(1);
                            }
                        }else{
                            s.setLimitSymptoms(1);
                        }
                        
                        s.setHistorySort(0);//设置默认值
                        if(r.getCell(20)!=null){
                            String value = r.getCell(20).toString();
                            if(value.equalsIgnoreCase("既往史")){
                                s.setHistorySort(1);
                            }else if(value.equalsIgnoreCase("诱因")){
                                s.setHistorySort(2);
                            }else if(value.equalsIgnoreCase("药物服用史")){
                                s.setHistorySort(3);
                            }else{
                                s.setHistorySort(0);
                            }
                        }else{
                            s.setHistorySort(0);
                        }
                        if(r.getCell(21)!=null){
                            s.setDegree(r.getCell(21).toString());
                        }
                        if(r.getCell(22)!=null){
                            s.setNature(r.getCell(22).toString());
                        }
                        if(r.getCell(23)!=null){
                            s.setFactor(r.getCell(23).toString());
                        }
                        if(r.getCell(24)!=null){
                            s.setTimes(r.getCell(24).toString());
                        }
                        if(r.getCell(25)!=null){
                            String med = r.getCell(25).toString();
                            s.setMedicine(med);
                            if(med!=null && med!=""){
                                String me = med.replaceAll("（","\\(").replaceAll("）","\\)").replaceAll("，",",");
                                ill.setMedicine(me);
                                String[] a = me.split("、");
                                if(a.length>0){
                                    for(String aa : a){
                                        String aaa = aa.replaceAll("\\(|\\)", "");
                                        String[] b = aaa.split(",");
                                        for(String bb : b){
                                            if(bb!=""){
                                                medicines.add(bb);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if(r.getCell(26)!=null){
                            s.setSdown((Double)r.getCell(26).getNumericCellValue());
                        }
                        if(r.getCell(27)!=null){
                            s.setSup((Double)r.getCell(27).getNumericCellValue());
                        }
                        if(r.getCell(28)!=null){
                            s.setDescription(r.getCell(28).toString());
                        }
                        
                        s.setWarning(1);//设置默认值
                        if(r.getCell(29)!=null){
                            s.setWarning((int)r.getCell(29).getNumericCellValue());
                        }else{
                            s.setWarning(1);
                        }
                        syms.add(s);
                    }
                }

                ill.setCreateTime(new Date());
                if(ages == null ||  ages.size()<=0){
                    return ResultModel.fail("该疾病年龄输入为空或年龄输入格式不对", null);
                }
                if(ill.getSex()==null){
                    return ResultModel.fail("该疾病性别输入为空或性别输入格式不对", null);
                }
                if(isAllAges){
                    Set<AgeSelect> isAllAgeList = new HashSet<AgeSelect>();
                    for(int i=1;i<=7;i++){
                        AgeSelect aa = new AgeSelect();
                        aa.setIllness(ill);
                        aa.setAgeOption(i);
                        isAllAgeList.add(aa);
                    }
                    ill.setAges(isAllAgeList);
                }else{
                    ill.setAges(ages);
                }
                
                if(syms == null || syms.size()<=0){
                    return ResultModel.fail("该疾病没有任何病症或病症输入格式不对", null);
                }
                ill.setSymptoms(syms);
                
                if(durations == null || durations.size()<=0){
                    return ResultModel.fail("该疾病没有任何发病时间或输入格式不对", null);
                }
                ill.setDurations(durations);
            }
            if(ill.getIllness()==null){
                return ResultModel.fail("导入失败", null);
            }
            ill.setAuthor(adminCode);
            for(String medi : medicines){
                NewCreatedMedicine newCM = new NewCreatedMedicine();
                MedicalDB mdb = medicalDBDao.findByName(medi);
                NewCreatedMedicine ncm = newCreatedMedicineDao.findByName(medi);
                if(mdb==null){
                    if(ncm==null){
                        newCM.setIsFlag(0);
                        newCM.setMedicineName(medi);
                        newCreatedMedicineDao.persist(newCM);
                    }else{
                        ncm.setIsFlag(0);
                        newCreatedMedicineDao.merge(ncm);
                    }
                }else{
                    if(ncm==null){
                        newCM.setIsFlag(1);
                        newCM.setMedicineName(medi);
                        newCreatedMedicineDao.persist(newCM);
                    }else{
                        ncm.setIsFlag(1);
                        newCreatedMedicineDao.merge(ncm);
                    }
                }
            }
            illnessDao.persist(ill);
            fileIn.close();      
            return ResultModel.success("导入成功", null);
        } catch (FileNotFoundException e1) {
            LOGGER.error("FileNotFoundException",e1);
            return ResultModel.fail("导入失败", null);
        } catch (IOException e2) {
            LOGGER.error("IOException",e2);
            return ResultModel.fail("导入失败", null);
        } catch (InvalidFormatException e) {
            LOGGER.error("InvalidFormatException",e);
            return ResultModel.fail("导入失败", null);
        }
    }

    @Override
    @Transactional(value = "medicalTM", readOnly=true)
    public List<ExportIllnessModel> exportIllness(String illness) {
        Illness ill = illnessDao.getIllnessRecortByIllness(illness);
        if(ill==null){
            return null;
        }
        List<ExportIllnessModel> list = new ArrayList<ExportIllnessModel>();
        Set<Symptom> symps = ill.getSymptoms();
        int flag = 0;
        for(Symptom s : symps){
            ExportIllnessModel e = new ExportIllnessModel();
            if(flag==0){
                e.setIllness(ill.getIllness());
                e.setLevelOneSubject(ill.getLevelOneSubject());
                e.setLevelTwoSubject(ill.getLevelTwoSubject());
                Integer sex = ill.getSex();
                if(sex==0){
                    e.setSex("男");
                }else if(sex==1){
                    e.setSex("女");
                }else{
                    e.setSex("全部");
                }
                e.setAssistantExam(ill.getAssistantExam());
                e.setScheme(ill.getScheme());
                e.setDuration(ill.getDuration());
                e.setPathogen(ill.getPathogen());
                e.setMedicine(ill.getMedicine());
                Integer limitNum = ill.getLimitNum();
                if(limitNum==null){
                    e.setLimitNum("0");
                }else{
                    e.setLimitNum(""+ill.getLimitNum());
                }
                e.setWarning(""+ill.getWarning());
                flag ++;
            }
            e.setSymptom(s.getSymptom());
            e.setDegree(s.getDegree());
            e.setSympMedicine(s.getMedicine());
            e.setNature(s.getNature());
            e.setTimes(s.getTimes());
            Double sdown = s.getSdown();
            if(sdown==null){
                e.setSdown("");
            }else{
                e.setSdown(""+s.getSdown());
            }
            Double sup = s.getSup();
            if(sup==null){
                e.setSup("");
            }else{
                e.setSup(""+s.getSup());
            }
            String parts = s.getParts();
            if(!parts.equalsIgnoreCase("其它")){
                e.setParts(parts);
            }else{
                e.setParts("");
            }
            e.setDescription(s.getDescription());
            Integer historySort = s.getHistorySort();          
            if(historySort==null){
                e.setHistorySort("");
            }else if(historySort==0){
                e.setHistorySort("");
            }else if(historySort==1){
                e.setHistorySort("既往史");
            }else if(historySort==2){
                e.setHistorySort("诱因");
            }else if(historySort==3){
                e.setHistorySort("药物服用史");
            }else{
                e.setHistorySort("");
            }
            e.setIncentive(s.getIncentive());
            Integer isImportant = s.getIsImportant();
            if(isImportant==0){
                e.setIsImportant("是");
            }else{
                e.setIsImportant("");
            }
            e.setMedicineHistory(s.getMedicineHistory());
            e.setPastHistory(s.getPastHistory());
            e.setSympWarning(""+s.getWarning());
            Integer isLimitSymptoms = s.getLimitSymptoms();
            if(isLimitSymptoms==0){
                e.setIslimitSymptoms("是");
            }else{
                e.setIslimitSymptoms("");
            }
            e.setFactor(s.getFactor());
            Integer sympsex = s.getSex();
            if(sympsex==0){
                e.setSympSex("男");
            }else if(sympsex==1){
                e.setSympSex("女");
            }else{
                e.setSympSex("全部");
            }
            list.add(e);
        }
        Set<AgeSelect> ages = ill.getAges();
        List<AgeSelect> alist = new ArrayList<AgeSelect>(ages);
        if(alist.size()<7){
            for(int i=0;i<alist.size();i++){
                Integer age = alist.get(i).getAgeOption();
                if(age==null){
                    
                }else if(age==1){
                    list.get(i).setAge("0-30天");
                }else if(age==2){
                    list.get(i).setAge("31天-3岁");
                }else if(age==3){
                    list.get(i).setAge("4-8岁");
                }else if(age==4){
                    list.get(i).setAge("9-14岁");
                }else if(age==5){
                    list.get(i).setAge("15-35岁");
                }else if(age==6){
                    list.get(i).setAge("36-64岁");
                }else if(age==7){
                    list.get(i).setAge("65岁以上");
                }else{
                    
                }
            }
        }else if(alist.size()==7){
            list.get(0).setAge("全年龄段");
        }else{
            
        }
        return list;
    }

    @Override
    @Transactional(value = "medicalTM", rollbackFor=Exception.class)
    public ResultModel synAllIllMedicines() {
        try {
            List<Illness> list = illnessDao.getAllIllness();
            Set<String> set = new HashSet<String>();
            for(Illness i : list){
                String illMedicine = i.getMedicine();
                if(illMedicine!=null && illMedicine!=""){
                    String ime = illMedicine.replaceAll("（","\\(").replaceAll("）","\\)").replaceAll("，",",");
                    String[] a = ime.split("、");
                    if(a.length>0){
                        for(String aa : a){
                            String aaa = aa.replaceAll("\\(|\\)", "");
                            String[] b = aaa.split(",");
                            for(String bb : b){
                                if(bb!=""){
                                    set.add(bb);
                                }
                            }
                        }
                    }
                }

                for(Symptom s : i.getSymptoms()){
                    String symMedicine = s.getMedicine();
                    if(symMedicine!="" && symMedicine!=null){
                        String sme = symMedicine.replaceAll("（","\\(").replaceAll("）","\\)").replaceAll("，",",");
                        String[] c = sme.split("、");
                        if(c.length>0){
                            for(String cc : c){
                                String ccc = cc.replaceAll("\\(|\\)", "");
                                String[] d = ccc.split(",");
                                for(String dd : d){
                                    if(dd!=""){
                                        set.add(dd);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            for(String medi : set){
                NewCreatedMedicine newCM = new NewCreatedMedicine();
                MedicalDB mdb = medicalDBDao.findByName(medi);
                NewCreatedMedicine ncm = newCreatedMedicineDao.findByName(medi);
                if(mdb==null){
                    if(ncm==null){
                        newCM.setIsFlag(0);
                        newCM.setMedicineName(medi);
                        newCreatedMedicineDao.persist(newCM);
                    }else{
                        ncm.setIsFlag(0);
                        newCreatedMedicineDao.merge(ncm);
                    }
                }else{
                    if(ncm==null){
                        newCM.setIsFlag(1);
                        newCM.setMedicineName(medi);
                        newCreatedMedicineDao.persist(newCM);
                    }else{
                        ncm.setIsFlag(1);
                        newCreatedMedicineDao.merge(ncm);
                    }
                }
            }
            return ResultModel.success("同步成功", null);
        } catch (Exception e) {
            LOGGER.error("synAllIllMedicines fail",e);
        }
        return ResultModel.fail("同步失败", null);
    }

}
